<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 这两资源下载太慢，用本地文件代替 -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist/build/pdf.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist/build/pdf.worker.js"></script> -->
    <script src="./static/pdf.js"></script>
    <script src="./static/pdf.worker.js"></script>
    <style>
      #pdfCOntainer {
        position: fixed;
        top: 100px;
        width: 100%;
        height: calc(100% - 100px);
      }
    </style>
  </head>
  <body>
    <input type="file" name="fileList" id="fileList" />
    <div>pdf阅读区</div>
    <div id="pdfContainer"></div>
    <script>
      const fileEle = document.getElementById("fileList");
      fileEle.addEventListener("change", (e) => {
        let files = e.target.files;
        let reader = new FileReader();
        // 打印出文件信息
        console.log(
          `文件信息:文件名称 ${files[0].name}; 文件大小 ${files[0].size}; 文件类型 ${files[0].type}`
        );
        reader.readAsArrayBuffer(files[0]);
        reader.onload = () => {
          loadPdf(reader.result);
        };
      });

      const loadPdf = async (file) => {
        const loadingTask = window.pdfjsLib.getDocument(file);
        const scale = 1.5;
        const pdfContainer = document.getElementById("pdfContainer");

        const pdf = await loadingTask.promise;
        // 渲染所有页面到canvas上
        var renderPage = function (num) {
          pdf.getPage(num).then(function (page) {
            var canvas = document.createElement("canvas");
            var context = canvas.getContext("2d");
            var viewport = page.getViewport({ scale: scale });

            // 调整canvas的高度以容纳新的页面
            canvas.height += viewport.height;
            canvas.width = viewport.width;

            // 渲染页面到canvas上
            var renderContext = {
              canvasContext: context,
              viewport: viewport,
            };

            var renderTask = page.render(renderContext);
            renderTask.promise.then(function () {
              // 将canvas添加到容器中
              canvas.classList.add("pdf-page");
              pdfContainer.appendChild(canvas);
              // 页面渲染完成，继续渲染下一页（如果有）
              if (num + 1 <= pdf.numPages) {
                renderPage(num + 1);
              } else {
                console.log("All pages rendered");
              }
            });
          });
        };

        // 从第一页开始渲染
        renderPage(1);
      };
    </script>
  </body>
</html>
